package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.data.ReqSetUserHeadImg
import com.hoow.shakoow.ai.data.ReqSetUserSignature
import com.hoow.shakoow.ai.data.ReqSetUserName
import com.hoow.shakoow.ai.enums.ProductEditEnum
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.base.BaseActivityConnectionAction
import com.hoow.shakoow.components.dialog.ImagePickerDialog
import com.hoow.shakoow.components.dialog.MessageDialog
import com.hoow.shakoow.components.dialog.UpdateNickNameAndGenderDialog
import com.hoow.shakoow.components.dialog.UpdateSignatureDialog
import com.hoow.shakoow.ai.data.ReqImageUpload
import com.hoow.shakoow.databinding.ActivityUserDetailSelfBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.bumptech.glide.Glide
import com.hoow.shakoow.shake.msgNotify.GreetMsgListener
import com.hoow.shakoow.shake.msgNotify.GreetMsgNotify
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil
import java.io.File


/** 用户详情页 */
@SuppressLint("CustomSplashScreen")
class UserDetailSelfActivity : BaseActivity(), BaseActivityConnectionAction, View.OnClickListener {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserDetailSelfBinding

    // 打招呼消息通知
    private lateinit var mGreetMsgNotify: GreetMsgNotify

    //调起相机
    private var mImageIntent: Intent? = null
    private var mImageCameraActivityResultLauncher: ActivityResultLauncher<Intent>? = null
    private var mImageFilePath = ""

    //调起相册
    private var mImageAlbumActivityResultLauncher: ActivityResultLauncher<String>? = null

    // 姓名
    private var mName: String = ""

    // 签名
    private var mSignature: String = ""

    // 性别
    private var mGender: Int = 0

    // 是否跳转相册页
    private var mIsToAblumPage = false

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.user_detail_self.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserDetailSelfBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity")
    override fun onContentViewBinded() {
        try {
            //初始化拍照与选择图片回调
            registerTakePicActivityResultCallback()
            registerAlbumActivityResultCallback()

            // 上传图片返回
            mNetworkViewModel.onUploadFileLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isNotBlank()) {
                            mNetworkViewModel.mImageUrl = result

                            // 设置用户头像
                            mNetworkViewModel.setUserHeadImg(ReqSetUserHeadImg(imgUrl = result))

                        } else {
                            MessageDialog.showDialog(
                                fragmentManager = supportFragmentManager,
                                message = getString(R.string.ai_please_upload_image_first),
                            )
                        }
                    }
                }
            }

            // 设置用户头像返回
            mNetworkViewModel.onSetUserHeadImgLiveData.observe(this) {
                if (it.isSuccess) {
                    // 获取用户详情
                    mNetworkViewModel.getUserInfo(ReqAiBase())
                }
            }

            // 获取用户详情回调
            mNetworkViewModel.onGetUserInfoLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        // 设置图像
                        result.headImg?.let { url ->
                            if (url.isValidLink()) {
                                Glide.with(mActivityBinding.imageUserAvatarValue)
                                    .load(url)
                                    .into(mActivityBinding.imageUserAvatarValue)
                            }
                        }

                        // 设置昵称
                        mActivityBinding.textUserNickNameValue.text = result.name
                        mName = result.name ?: ""

                        // 设置性别
                        mActivityBinding.textUserGenderValue.text = result.getGenderDisplay()
                        try {
                            mGender = (result.sex ?: "0").toInt()
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                        // 设置相册
                        mActivityBinding.imageUserAlbum1.visibility = View.INVISIBLE
                        mActivityBinding.imageUserAlbum2.visibility = View.INVISIBLE
                        mActivityBinding.imageUserAlbum3.visibility = View.INVISIBLE

                        result.userPhotos?.let { photos ->
                            if (photos.isNotEmpty()) {
                                mActivityBinding.imageUserAlbum1.visibility = View.VISIBLE
                                val imgUrl = photos[0].imgUrl ?: ""
                                if (imgUrl.isValidLink()) {
                                    Glide.with(mActivityBinding.imageUserAlbum1)
                                        .load(imgUrl)
                                        .into(mActivityBinding.imageUserAlbum1)
                                }
                            }
                            if (photos.size > 1) {
                                mActivityBinding.imageUserAlbum2.visibility = View.VISIBLE
                                val imgUrl = photos[1].imgUrl ?: ""
                                if (imgUrl.isValidLink()) {
                                    Glide.with(mActivityBinding.imageUserAlbum2)
                                        .load(imgUrl)
                                        .into(mActivityBinding.imageUserAlbum2)
                                }
                            }
                            if (photos.size > 2) {
                                mActivityBinding.imageUserAlbum3.visibility = View.VISIBLE
                                val imgUrl = photos[2].imgUrl ?: ""
                                if (imgUrl.isValidLink()) {
                                    Glide.with(mActivityBinding.imageUserAlbum3)
                                        .load(imgUrl)
                                        .into(mActivityBinding.imageUserAlbum3)
                                }
                            }
                        }

                        // 设置个性签名
                        mActivityBinding.textUserSignatureValue.text = result.description
                        mSignature = result.description ?: ""

                        // 设置会员剩余天数
                        mActivityBinding.textUserVipValidDaysValue.text =
                            getString(R.string.shake_vip_remain_days, result.vipRemindDays)
                    }
                }
            }

            // 设置昵称与性别回调
            mNetworkViewModel.onSetUserNameLiveData.observe(this) {
                if (it.isSuccess) {
                    // 获取用户详情
                    mNetworkViewModel.getUserInfo(ReqAiBase())
                }
            }

            // 设置签名回调
            mNetworkViewModel.onSetUserSignatureLiveData.observe(this) {
                if (it.isSuccess) {
                    // 获取用户详情
                    mNetworkViewModel.getUserInfo(ReqAiBase())
                }
            }

            // 点击更新头像
            mActivityBinding.llUserAvatarBg.setOnClickListener(this)
            // 点击更新昵称
            mActivityBinding.llUserNickNameBg.setOnClickListener(this)
            // 点击更新签名
            mActivityBinding.llUserSignatureBg.setOnClickListener(this)
            // 点击相册
            mActivityBinding.llUserAblumBg.setOnClickListener(this)
            mActivityBinding.imageUserAlbumExt.setOnClickListener(this)
            mActivityBinding.imageUserAlbum1.setOnClickListener(this)
            mActivityBinding.imageUserAlbum2.setOnClickListener(this)
            mActivityBinding.imageUserAlbum3.setOnClickListener(this)
            // 剩余vip天数
            mActivityBinding.llUserVipValidDaysBg.setOnClickListener(this)
            // 点击打招呼的人
            mActivityBinding.llUserWhoGreetsBg.setOnClickListener(this)
            // 点击历史摇一摇
            mActivityBinding.llUserShakeHistoryBg.setOnClickListener(this)
            // 点击历史摇一摇-未读
            mActivityBinding.textAdapterUnReadCount.setOnClickListener(this)
            // 反馈
            mActivityBinding.textFeedback.setOnClickListener(this)
            mActivityBinding.textFeedback.addUnderLine()

            // 初始化消息通知
            mGreetMsgNotify = GreetMsgNotify(retrySec = 10)
            mGreetMsgNotify.setGreetMsgListener(object : GreetMsgListener {
                override fun onMsgDetected(unReadCount: Int) {
                    // 收到新消息
                    mActivityBinding.textAdapterUnReadCount.text = unReadCount.toString()
                    mActivityBinding.textAdapterUnReadCount.visibility = View.VISIBLE
                }

                override fun onNotMatchNewMsg() {
                    // 没有新消息要提示
                    mActivityBinding.textAdapterUnReadCount.text = "0"
                    mActivityBinding.textAdapterUnReadCount.visibility = View.GONE
                }
            })

            // 获取用户详情
            mNetworkViewModel.getUserInfo(ReqAiBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        if (mIsToAblumPage) {
            // 更新状态
            mIsToAblumPage = false

            // 获取用户详情
            mNetworkViewModel.getUserInfo(ReqAiBase())
        }

        // 获取未读消息
        mGreetMsgNotify.reloadGreetMsgNow()
    }

    override fun onDestroy() {
        mGreetMsgNotify.releaseResrouce()
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        when (v) {
            // 点击相册
            mActivityBinding.llUserAblumBg -> {
                mIsToAblumPage = true
                startToUserAblumSelfPage()

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_AVATAR_CLICK",
                    remark = ""
                )
            }
            mActivityBinding.imageUserAlbumExt -> {
                mIsToAblumPage = true
                startToUserAblumSelfPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_AVATAR_CLICK",
                    remark = ""
                )
            }
            mActivityBinding.imageUserAlbum1 -> {
                mIsToAblumPage = true
                startToUserAblumSelfPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_AVATAR_CLICK",
                    remark = ""
                )
            }
            mActivityBinding.imageUserAlbum2 -> {
                mIsToAblumPage = true
                startToUserAblumSelfPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_AVATAR_CLICK",
                    remark = ""
                )
            }
            mActivityBinding.imageUserAlbum3 -> {
                mIsToAblumPage = true
                startToUserAblumSelfPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_AVATAR_CLICK",
                    remark = ""
                )
            }
            // 剩余vip天数
            mActivityBinding.llUserVipValidDaysBg -> {
                startToUserRechargePage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_VIP_CLICK",
                    remark = ""
                )
            }
            // 点击打招呼的人
            mActivityBinding.llUserWhoGreetsBg -> {
                startToGreetHistoryPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_TO_GREE_CLICK",
                    remark = ""
                )
            }
            // 点击历史摇一摇
            mActivityBinding.llUserShakeHistoryBg -> {
                startToShakeHistoryPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_TO_SHAKE_CLICK",
                    remark = ""
                )
            }
            // 点击历史摇一摇-未读
            mActivityBinding.textAdapterUnReadCount -> {
                startToShakeHistoryPage()
                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_TO_GREE_CLICK",
                    remark = ""
                )
            }
            // 点击更新头像
            mActivityBinding.llUserAvatarBg -> {
                // 两种，拍照与选择相册
                ImagePickerDialog.showDialog(supportFragmentManager) { action ->
                    mNetworkViewModel.mImageAction = action
                    if (action == ImagePickerDialog.PICK_TYPE_ALBUM) {
                        openAblum()
                    } else if (action == ImagePickerDialog.PICK_TYPE_CAMER) {
                        requestExtPermissoins()
                    }
                }

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_UPDATE_AVATAR",
                    remark = ""
                )
            }
            // 点击更新昵称
            mActivityBinding.llUserNickNameBg -> {
                UpdateNickNameAndGenderDialog.showDialog(
                    supportFragmentManager,
                    mName,
                    mGender
                ) { name, gender ->
                    if (name.isNotBlank()) {
                        val reqSetUserName = ReqSetUserName(name = name, sex = gender)
                        mNetworkViewModel.setUserName(reqSetUserName)
                    }
                }

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_UPDATE_NICKNAME",
                    remark = ""
                )
            }
            // 点击更新签名
            mActivityBinding.llUserSignatureBg -> {
                UpdateSignatureDialog.showDialog(
                    supportFragmentManager,
                    mSignature
                ) { signature ->
                    if (signature.isNotBlank()) {
                        val reqSetUserSignature = ReqSetUserSignature(description = signature)
                        mNetworkViewModel.setUserSignature(reqSetUserSignature)
                    }
                }

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_UPDATE_SIGN",
                    remark = ""
                )
            }
            // 反馈
            mActivityBinding.textFeedback -> {
                startToUserFeedbackPage()

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "USER_FEEDBACK_CLICK",
                    remark = ""
                )
            }
        }
    }

    override fun onPermissionsRequestAllPass() {
        //调起相机
        mImageCameraActivityResultLauncher?.launch(mImageIntent)
    }

    override fun takePicture() {
        //调起相机前，申请权限
        requestExtPermissoins()
    }

    override fun openAblum() {
        //调起相册
        mImageAlbumActivityResultLauncher?.launch("image/*")
    }

    /** 注册拍照回调 */
    @SuppressLint("Recycle", "Range")
    private fun registerTakePicActivityResultCallback() {
        try {
            //front
            mImageFilePath =
                getCacheImageFilePath("icfront")
            val imageFile = File(mImageFilePath)
            val imageUri: Uri = if (Build.VERSION.SDK_INT < 24) {
                Uri.fromFile(imageFile)
            } else {
                FileProvider.getUriForFile(this, "$packageName.file_provider", imageFile)
            }
            mImageIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                .apply { putExtra(MediaStore.EXTRA_OUTPUT, imageUri) }
            mImageCameraActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                    try {
                        pickResultFromCameraActivity(
                            outFilePath = mImageFilePath,
                            result = result,
                            convertFinish = { covetPath, bitmap ->
                                onHandlerImagePickResult(
                                    covetPath = covetPath,
                                    bitmap = bitmap
                                )
                            })
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 注册相册回调 */
    private fun registerAlbumActivityResultCallback() {
        try {
            mImageAlbumActivityResultLauncher =
                registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
                    try {
                        try {
                            pickResultFromAlbumActivity(
                                result = uri,
                                convertFinish = { covetPath, bitmap ->
                                    onHandlerImagePickResult(
                                        covetPath = covetPath,
                                        bitmap = bitmap
                                    )
                                })
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 处理选择/拍照回调 */
    private fun onHandlerImagePickResult(
        covetPath: String?,
        bitmap: Bitmap?
    ) {
        var validPath = false
        covetPath?.let {
            mNetworkViewModel.mImagePath = it
            validPath = true
        }

        var validBitmap = false
        bitmap?.let {
            mNetworkViewModel.mImageBitmap = it
            validBitmap = true
        }

        if (validPath and validBitmap) {
            //上传图片
            mNetworkViewModel.uploadFile(
                ReqImageUpload(
                    filePath = mNetworkViewModel.mImagePath,
                    cardType = ProductEditEnum.IMAGE_TO_IMAGE.name
                )
            )
        } else {
            MessageDialog.showDialog(
                fragmentManager = supportFragmentManager,
                message = getString(R.string.ai_please_upload_image_first),
            )
        }
    }

    /** 请求相机权限 */
    private fun requestExtPermissoins() {
        requestSpecPermissions(arrayOf(android.Manifest.permission.CAMERA))
    }
}